<template>
  <div id="progress-loop" ref="chartDom" style="width: 100%; height: 100%;"></div>
</template>

<script setup lang="ts" name="dataScreen">
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';
import { debounce } from "@/utils";
import * as echarts from 'echarts';

const props = defineProps({
  chartData: {
    type: Object,
    default: () => ({
      title: '',
      data: []
    }),
  },
});

const chartDom = ref();
let myChart = null;

// Function to initialize or update the chart
const initChart = () => {
  if (myChart) {
    const option = {
      title: {
        text: props.chartData.title || 'No Title',
        textStyle: {
          fontSize: 12, // 根据设计调整
          color: "#fff",
        },
        left: "left",
        top: "0",
      },
      tooltip: {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      legend: {
        show: true,
        left: 'center',
        top: 'bottom',
        itemWidth: 8,
        itemHeight: 8,
        textStyle: {
          fontSize: 10,
          color: '#fff',
        },
      },
      series: [
        {
          name: props.chartData.title || 'No Title',
          type: 'pie',
          radius: '55%',
          center: ['50%', '45%'],
          data: props.chartData.data || [],
          label: {
            show: true,
            // alignTo: 'edge',                // 标签对齐到饼图的边缘
            formatter: '{c}\n {d}%',  // 标签显示格式 name 换行显示 value 和百分比
            minMargin: 5,                   // 标签与饼图边缘的最小距离
            edgeDistance: 5,                // 标签与边缘的最小距离
            lineHeight: 15,                 // 设置行高，增加文本行间距
            textStyle: {
              color: '#fff',                // 确保这里是白色
              fontSize: 10,
            },
            overflow: 'break',              // 处理长文本时，自动换行
          },
          labelLine: {
            show: true,                     // 显示连接线
            length: 10,                     // 连接线的长度
            length2: 10                  // 第二段连接线的长度
          }
        }
      ]
    };
    myChart.setOption(option);
  }
};

// 处理图表缩放
const handleChartResize = debounce(() => {
  if (myChart) {
    myChart.resize();
  }
}, 100);

// 组件挂载时
onMounted(() => {
  nextTick(() => {
    myChart = echarts.init(chartDom.value);
    initChart();
  });

  window.addEventListener("resize", handleChartResize);
});

// 监视数据变化
watch(() => props.chartData, () => {
  initChart();
}, { deep: true });

// 组件卸载时清理
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleChartResize);
  if (myChart) {
    myChart.dispose();
  }
});
</script>
